package demon2;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpSever {
    private ServerSocket severSocket=null;
    public TcpSever(int port){
        try {
            severSocket=new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true) {
            try (Socket socket = severSocket.accept()) {
                Thread thread=new Thread(()->{
                   processConnectio(socket);
                });
                thread.start();
            }
        }
    }
    private void processConnectio(Socket socket){
        System.out.printf("[%s:%d]\n", socket.getInetAddress(), socket.getPort());
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            while (true) {
                Scanner scanner = new Scanner(inputStream);
                if (!scanner.hasNext()) {
                    System.out.printf("[%s:%d] 客户端下线\n", socket.getInetAddress(), socket.getPort());
                    break;
                }
                String request = scanner.next();
                String respon = process(request);
                outputStream.write(respon.getBytes());
                System.out.printf("[%s:%d] req=%s,resp=%s\n", socket.getInetAddress(), socket.getPort(), request, respon);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String process (String request){
        return request + "\n";
    }

    public static void main (String[]args){
//        TcpSever tcpSever = new TcpSever(9090);
//        try {
//            tcpSever.start();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        while(true){
            Thread thread=new Thread(()->{
                System.out.println("hello");
            });
            thread.start();
        }

    }
}

